<template>
  <div class="dashboard">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon customer">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总客户数</div>
              <div class="card-value">{{ overviewData.totalCustomers }}</div>
              <div class="card-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.customerGrowth }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon order">
              <el-icon><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总订单数</div>
              <div class="card-value">{{ overviewData.totalOrders }}</div>
              <div class="card-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.orderGrowth }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总营收</div>
              <div class="card-value">{{ formatAmount(overviewData.totalRevenue) }}</div>
              <div class="card-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.revenueGrowth }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon avg">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">平均订单额</div>
              <div class="card-value">{{ formatAmount(overviewData.avgOrderValue) }}</div>
              <div class="card-trend neutral">
                <el-icon><Minus /></el-icon>
                0%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 销售趋势图 -->
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">销售趋势</span>
              <el-radio-group v-model="trendPeriod" size="small" @change="updateSalesTrend">
                <el-radio-button label="7d">近7天</el-radio-button>
                <el-radio-button label="30d">近30天</el-radio-button>
                <el-radio-button label="90d">近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="salesTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 客户分布饼图 -->
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span class="card-title">客户地区分布</span>
          </template>
          <div ref="customerDistChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 产品销售排行和最新订单 -->
    <el-row :gutter="20" class="bottom-section">
      <!-- 产品销售排行 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <span class="card-title">产品销售排行</span>
          </template>
          <el-table :data="productSales" stripe>
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="quantity" label="销量" width="80" />
            <el-table-column prop="value" label="销售额" width="150">
              <template #default="{ row }"> {{ formatAmount(row.value) }} </template>
            </el-table-column>
            <el-table-column label="占比" width="100">
              <template #default="{ row }">
                <el-progress
                  :percentage="getPercentageNumber(row.value, totalSales)"
                  :show-text="false"
                  :stroke-width="8"
                />
                {{ getPercentage(row.value, totalSales) }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 最新订单 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">最新订单</span>
              <el-button type="primary" size="small" @click="$router.push('/order/list')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentOrders" stripe>
            <el-table-column prop="orderNo" label="订单号" width="200" />
            <el-table-column prop="customerName" label="客户" />
            <el-table-column prop="finalAmount" label="金额" width="100">
              <template #default="{ row }"> {{ formatAmount(row.finalAmount) }} </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusType(row.status)" size="small">
                  {{ getOrderStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { User, Document, Money, DataAnalysis, TrendCharts, Minus } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getBusinessOverview, getSalesTrend, getProductSales } from '@/api/analytics'
import { getOrderList } from '@/api/order'
import { formatAmount, getOrderStatusLabel, getPercentage, getPercentageNumber } from '@/utils'
import type { ECharts } from 'echarts'

// 数据概览
const overviewData = ref({
  totalCustomers: 0,
  totalOrders: 0,
  totalRevenue: 0,
  avgOrderValue: 0,
  customerGrowth: 0,
  orderGrowth: 0,
  revenueGrowth: 0,
})

// 图表实例
const salesTrendChart = ref<HTMLElement>()
const customerDistChart = ref<HTMLElement>()
let salesChart: ECharts | null = null
let distChart: ECharts | null = null

// 趋势图时间周期
const trendPeriod = ref('7d')

// 产品销售数据
const productSales = ref<any[]>([])
const totalSales = ref(0)

// 最新订单
const recentOrders = ref<any[]>([])

// 获取订单状态类型
const getOrderStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    confirmed: 'primary',
    production: 'info',
    delivered: 'success',
    cancelled: 'danger',
  }
  return statusMap[status] || 'info'
}

// 初始化销售趋势图
const initSalesTrendChart = () => {
  if (!salesTrendChart.value) return

  salesChart = echarts.init(salesTrendChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: ['销售额', '订单数'],
    },
    xAxis: {
      type: 'category',
      data: [],
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        position: 'left',
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
      },
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: [],
        itemStyle: {
          color: '#1890ff',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.1)' },
            ],
          },
        },
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: [],
        itemStyle: {
          color: '#52c41a',
        },
      },
    ],
  }

  salesChart.setOption(option)
}

// 初始化客户分布图
const initCustomerDistChart = () => {
  if (!customerDistChart.value) return

  distChart = echarts.init(customerDistChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '客户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [],
      },
    ],
  }

  distChart.setOption(option)
}

// 更新销售趋势数据
const updateSalesTrend = async () => {
  try {
    const endDate = new Date().toISOString().split('T')[0]
    const startDate = new Date(Date.now() - parseInt(trendPeriod.value) * 24 * 60 * 60 * 1000)
      .toISOString()
      .split('T')[0]

    const { data } = await getSalesTrend({
      startDate,
      endDate,
      type: 'daily',
    })

    if (salesChart && data) {
      // 确保data是数组格式
      const trendData = Array.isArray(data) ? data : (data.list || [])
      salesChart.setOption({
        xAxis: {
          data: trendData.map((item: any) => item.date.split('-').slice(1).join('/')),
        },
        series: [
          {
            data: trendData.map((item: any) => item.amount),
          },
          {
            data: trendData.map((item: any) => item.orders),
          },
        ],
      })
    }
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
  }
}

// 加载数据
const loadData = async () => {
  try {
    // 加载概览数据
    const overviewRes = await getBusinessOverview()
    if (overviewRes.data) {
      overviewData.value = overviewRes.data
    }

    // 加载产品销售数据
    const productRes = await getProductSales()
    if (productRes.data) {
      // 确保data是数组格式
      const salesData = Array.isArray(productRes.data) ? productRes.data : (productRes.data.list || [])
      productSales.value = salesData.slice(0, 5)
      totalSales.value = salesData.reduce((sum: number, item: any) => sum + item.value, 0)
    }

    // 加载最新订单
    const orderRes = await getOrderList({ page: 1, pageSize: 5 })
    if (orderRes.data) {
      // 使用修复后的API返回格式
      recentOrders.value = orderRes.data.list ? orderRes.data.list.slice(0, 5) : []
    }

    // 更新客户分布图
    if (distChart) {
      const customerDist = [
        { name: '上海市', value: 1 },
        { name: '北京市', value: 1 },
        { name: '广东省', value: 2 },
        { name: '浙江省', value: 1 },
      ]

      distChart.setOption({
        series: [
          {
            data: customerDist,
          },
        ],
      })
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 窗口大小变化时重新调整图表
const handleResize = () => {
  salesChart?.resize()
  distChart?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化图表
  initSalesTrendChart()
  initCustomerDistChart()

  // 加载数据
  await loadData()
  await updateSalesTrend()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.card-icon.customer {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.order {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.revenue {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.avg {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.card-trend.neutral {
  color: #909399;
}

.card-trend .el-icon {
  margin-right: 4px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  height: 400px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.bottom-section {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-cards .el-col {
    margin-bottom: 16px;
  }

  .charts-section .el-col,
  .bottom-section .el-col {
    margin-bottom: 20px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
